package cn.imatu.framework.sms.manager;

import cn.imatu.framework.exception.BizException;
import cn.imatu.framework.sms.manager.entity.JMSmsReps;
import cn.imatu.framework.sms.manager.entity.JMSmsReq;
import cn.imatu.framework.sms.properties.JMSmsProperties;
import cn.imatu.framework.tool.core.StringUtils;
import cn.imatu.framework.tool.core.exception.Assert;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

/**
 * @author shenguangyang
 */
public class JMSmsManager implements ISmsManager<JMSmsReq, JMSmsReps> {
    private static final Logger log = LoggerFactory.getLogger(JMSmsManager.class);
    private final JMSmsProperties jmSmsProperties;
    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";
    private static final Integer SUCCESS_CODE = 200;
    private final RestTemplate restTemplate;

    public JMSmsManager(JMSmsProperties jmSmsProperties, RestTemplate restTemplate) {
        this.jmSmsProperties = jmSmsProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public JMSmsReps send(JMSmsReq req) {
        String appcode = jmSmsProperties.getAppCode();
        String mobile = StringUtils.toList(req.getPhoneNumbers(), ",", String.class).get(0);
        String value = Optional.ofNullable(req.getTemplateParam().getString("value")).orElseThrow(
                () -> new BizException("please input value"));

        String url = String.format(URL_TEMPLATE, mobile, req.getTemplateId(), value);
        HttpHeaders headers = new HttpHeaders();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization", " APPCODE " + appcode);
        HttpEntity<Object> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        try {
            HttpStatus statusCode = response.getStatusCode();
            String body = response.getBody();
            if (statusCode != HttpStatus.OK) {
                log.error("send sms fail, resp: {}, url: {}", body, url);
                return JMSmsReps.builder().isSuccess(false).code(String.valueOf(statusCode.value())).requestId("")
                        .bizId("").message(body).build();
            }
            Assert.notNull(body, "resp body is null");
            log.debug("sms resp: {}", body);
            JSONObject jsonObject = JSON.parseObject(body);
            Integer code = jsonObject.getInteger("code");
            String msg = jsonObject.getString("msg");
            // 本次请求ID
            String taskNo = jsonObject.getString("taskNo");
            Assert.notNull(code, url + " response code is null");
            if (SUCCESS_CODE.compareTo(code) == 0) {
                // 短信发送任务ID，可用于查询短信发送状态，建议保存
                String taskId = jsonObject.getJSONObject("data").getString("taskId");
                return JMSmsReps.builder().isSuccess(true).code(String.valueOf(code)).requestId(taskNo).bizId(taskId)
                        .message(msg).build();
            } else {
                return JMSmsReps.builder().isSuccess(false).code(String.valueOf(code)).requestId(taskNo).bizId("")
                        .message(msg).build();
            }

        } catch (Exception e) {
            throw e;
        }
    }
}
